<template>
    <div>
        <view style="padding: 15px;">
            <u-form ref="validateFormRef" :model="validateForm.value" :label-width="200">
                <u-form-item label="商品推荐模板" prop="id" required right-icon="arrow-right">
                    <u-input type="textarea" height="40" :clearable="false" :select-open="validateForm.controls.id.isShow"
                             v-model="validateForm.controls.id.textDesc"
                             placeholder="请选择商品推荐模板" @click="validateForm.controls.id.isShow = true; $forceUpdate();"></u-input>
                </u-form-item>

                <u-form-item label="关联商品（已关联的会被覆盖）" label-position="top" prop="goodsIds" required>
                    <scroll-view scroll-x="true">
                        <div style="border-bottom: 1px solid #eeeeee;">
                            <u-checkbox size="40" shape="circle" :value="allCheckbox" @change="onCheckboxChange($event, null)"
                                        key="allCheckbox" active-color="red">
                                <label>全选</label>
                            </u-checkbox>
                        </div>
                        <div :style="{'border-bottom': index !== goodsList.length - 1 ? '1px solid #eeeeee' : 'unset'}"
                             v-for="(item, index) in goodsList" :key="index">
                            <u-checkbox size="40" @change="onCheckboxChange($event, item)"
                                        :value="item.checked"
                                        :name="item.key"
                                        shape="circle"
                                        active-color="red"
                            ><label style="color: red;">{{item.templateName}}</label>{{item.title}}
                            </u-checkbox>
                        </div>
                    </scroll-view>
                </u-form-item>
            </u-form>

            <div style="padding-bottom: 60px;"></div>

            <u-select mode="single-column" label-name="name" value-name="code" :mask-close-able="false"
                      v-model="validateForm.controls.id.isShow" :list="validateForm.controls.id.options"
                      :default-value="validateForm.controls.id.defaultValue"
                      @cancel="validateForm.controls.id.isShow = false; $forceUpdate();"
                      @confirm="UFormUtil.selectSingleColumnConfirm($event, validateForm.controls.id)"></u-select>

        </view>

        <div class="custom-bottom-button">
            <label @click="submit">
                提交
            </label>
        </div>
    </div>
</template>

<script>
    import {CommonUtil} from "@/dev/core/utils/common.util";
    import {UFormUtil} from "@/dev/core/utils/u-form.util";
    import {TbGoodsDetailGoodsRecommendTemplateService} from "@/dev/services/tb-goods-detail-goods-recommend-template.service";

    export default {
        data() {
            return {
                allCheckbox: false,
                goodsList: [],
                validateForm: {
                    value: {
                        id: '',
                        goodsIds: '',
                    },
                    rules: {
                        id: [
                            {required: true, message: '必填项!', trigger: ['change', 'blur']},
                            {pattern: /^(?=.*\S).+$/, message: '必填项!', trigger: ['change', 'blur']}
                        ],
                        goodsIds: [
                            {required: true, message: '必填项!', trigger: ['change', 'blur']},
                            {pattern: /^(?=.*\S).+$/, message: '必填项!', trigger: ['change', 'blur']}
                        ],
                    }
                }
            }
        },
        onReady() {
            const _self = this;

            new TbGoodsDetailGoodsRecommendTemplateService().findTbGoodsDetailGoodsRecommendTemplateList({
                communityId: _self.globalVariable.userInfo.tbStore.communityId,
                storeId: _self.globalVariable.userInfo.tbStore.id
            }).then(result => {
                result.forEach(item => {
                    item.name = item['name'] + '--' + item['positionText'] + '--' + item['statusText'];
                    item.code = item.id;
                });

                UFormUtil.setOptions(_self.validateForm.controls.id, result);
                _self.$forceUpdate();
            });

            new TbGoodsDetailGoodsRecommendTemplateService().findTransferTbGoodsDetailGoodsRecommendTemplateList({
                communityId: _self.globalVariable.userInfo.tbStore.communityId,
                storeId: _self.globalVariable.userInfo.tbStore.id
            }).then(result => {
                result.forEach(item => {
                    item.checked = false;
                });
                _self.goodsList = result;
            });
        },
        methods: {
            // 选中任一checkbox时，由checkbox-group触发
            onCheckboxChange($event, item) {
                const _self = this;
                console.log($event, item);

                // 商品列表
                if (item) {
                    item.checked = $event.value;
                    if (_self.goodsList.filter(item => item.checked).length === 0) {
                        _self.allCheckbox = false;
                    } else if (_self.goodsList.filter(item => item.checked).length === _self.goodsList.length) {
                        _self.allCheckbox = true;
                    } else {
                        _self.allCheckbox = false;
                    }
                } else {  // 全选按钮
                    _self.allCheckbox = $event.value;

                    if (_self.allCheckbox) {
                        _self.goodsList.forEach(item => {
                            item.checked = true;
                        });
                    } else {
                        _self.goodsList.forEach(item => {
                            item.checked = false;
                        });
                    }
                }

                _self.$forceUpdate();

                let goodsIds = [];
                _self.goodsList.forEach(item => {
                    if (item.checked) {
                        goodsIds.push(item.key);
                    }
                });
                _self.validateForm.value.goodsIds = goodsIds.join(",");
                console.log(_self.validateForm.value.goodsIds);
            },
            submit() {
                const _self = this;
                this.$refs.validateFormRef.validate(valid => {
                    if (valid) {
                        console.log('验证通过', _self.validateForm.value);
                        CommonUtil.alert({
                            title: '提示！',
                            content: '确认提交吗？',
                            showCancel: true, // 是否显示取消按钮
                            success: function (res) {
                                if (res.cancel) { // 点击取消,默认隐藏弹框
                                } else { // 点击确定
                                    new TbGoodsDetailGoodsRecommendTemplateService().batchSaveAssignedTbGoodsDetailGoodsRecommendTemplates(_self.validateForm.value).then(result => {
                                        CommonUtil.toastNavigateBack('保存成功')
                                    });
                                }
                            }
                        });
                    } else {
                        console.log('验证失败');
                    }
                });
            }
        }
    };
</script>

<style lang="scss" scoped>
</style>
